<?php

namespace App\Http\Controllers;

use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class CategoryController extends Controller
{

    private $category;

    public function __construct(Category $category)
    {
        $this->category = $category;
    }

    public function add(Request $request){

        $validator = Validator::make($request->all(), [
            'name' => 'required|string|min:1,max:32|unique:t_category',
            'pid' => 'required|integer|min:0',
        ]);

        if ($validator->fails()) {

            return $this->error($validator->errors());
        }

        if(!$this->category->isExitsById($request['pid'])){

            return $this->error('父类不存在');

        }

        $data = [
            'name' => $request['name'],
            'pid' => $request['pid']
        ];

        $model = $this->category->create($data);

        if(!$model){
            return $this->error('插入失败');
        }

        return $this->success(['id' => $model->id]);

    }

    public function update(){
        return "update";
    }

    public function delete($id){

        $model = $this->category->find($id);

        if(!$model){
            return ['code' => 0,'message' => '请求失败','data' => '该数据不存在'];
        }

        $child = $this->category->where('pid' , $model->id)->get()->toArray();


        if($child){
            return ['code' => 0,'message' => '请求失败','data' => '该分类有子类不能删除'];
        }

        $isSuccess = $model->delete();

        if(!$isSuccess){
            return ['code' => 0,'message' => '请求失败','data' => '删除失败'];
        }
        return ['code' => 0,'message' => '请求成功','data' => '删除成功'];
    }

    public function search(Request $request){

        $validator = Validator::make($request->all(), [
            'name' => 'string|min:1,max:32',

        ]);

        if ($validator->fails()) {

            return ['code' => 0,'message' => '请求失败','data' => $validator->errors()];
        }

        if(empty($request['name'])){
            $data = $this->category->all();

        }else{
            $data = $this->category->where('name','like',"%".$request['name']."%")->get();
        }


        return ['code' => 0,'message' => '请求成功','data' => $data->toArray()];
    }
}
